# 打开文件
file = open("F:\PythonBasic\PythonBasic\PythonBasic\example.txt", "r")
 
# 读取文件内容
content = file.read()
print(content)
 
# 关闭文件
file.close()

with open("F:\PythonBasic\PythonBasic\PythonBasic\example.txt", "r") as file:
    content = file.read()
    print(content)  # 输出文件的所有内容


with open("F:\PythonBasic\PythonBasic\PythonBasic\example.txt", "r") as file:
    line = file.readline()
    while line:
        print(line, end="")  # 输出每一行
        line = file.readline()

with open("F:\PythonBasic\PythonBasic\PythonBasic\example.txt", "r") as file:
    lines = file.readlines()
    print(lines)  # 输出：['第一行内容\n', '第二行内容\n', ...]

with open("F:\PythonBasic\PythonBasic\PythonBasic\example.txt", "r") as file:
    for line in file:
        print(line, end="")  # 输出每一行

with open("F:\PythonBasic\PythonBasic\PythonBasic\example.txt", "w") as file:
    file.write("第一行内容\n")
    file.write("第二行内容\n")

import os
 
os.rename("F:\PythonBasic\PythonBasic\PythonBasic\example.txt", "renamed_example.txt")
print("文件已重命名")  #F:\PythonBasic\PythonBasic\renamed_example.txt

import tensorflow as tf

with tf.io.gfile.GFile("F:\PythonBasic\PythonBasic\PythonBasic\example.txt", "r") as file:
    content = file.read()
    print(content)  # 输出文件的所有内容

with open("example.txt", "r", encoding="gbk") as file:
    content = file.read()
    print(content)


with open("renamed_example.txt", "r") as file:
    # 初始位置
    print("初始位置:", file.tell())  # 输出：0
 
    # 读取前 5 个字符
    content = file.read(5)
    print("读取内容:", content)      # 输出：文件的前 5 个字符
 
    # 当前文件指针位置
    print("当前位置:", file.tell())  # 输出：5
 
    # 移动文件指针到文件开头
    file.seek(0)
    print("重置位置:", file.tell())  # 输出：0

with open("example.jpg", "rb") as file:
    binary_data = file.read(10)  # 读取前 10 个字节
    print(binary_data)           # 输出：二进制数据


import portalocker
 
with open("renamed_example.txt", "a") as file:
    # 加锁
    portalocker.lock(file, portalocker.LOCK_EX)
    file.write("写入受锁保护的数据\n")
    # 解锁
    portalocker.unlock(file)



import mmap
 
with open("renamed_example.txt", "r+b") as file:
    # 将文件映射到内存
    mm = mmap.mmap(file.fileno(), 0)
 
    # 读取文件前 10 个字节
    print(mm[:10])
 
    # 修改文件内容
    mm[0:5] = b"Hello"
    mm.close()